/**
* @project admin-go-api
* @name sysDept
* @descriptions 部门数据层
* @author 寒锋
* @date 2023-12-18 14:32:43
 */

package dao

import (
	"admin-go-api/api/entity"
	"admin-go-api/common/util"
	. "admin-go-api/pkg/db"
	"errors"
	"time"
)

// GetSysDeptByName 根据名称查询部门信息
func GetSysDeptByName(name string, id uint) (sysDept entity.SysDept) {
	model := Db.Where("dept_name = ?", name)
	if id != 0 {
		model = model.Where("dept_id <> ?", id)
	}
	model.First(&sysDept)
	return sysDept
}

// GetSysDeptById 根据id获取部门信息
func GetSysDeptById(id uint) (sysDept entity.SysDept) {
	Db.First(&sysDept, id)
	return sysDept
}

// CreateSysDept 添加部门
func CreateSysDept(sysDept entity.SysDept) bool {
	sysDeptByName := GetSysDeptByName(sysDept.DeptName, 0)
	if sysDeptByName.DeptId > 0 {
		return false
	}
	data := entity.SysDept{
		ParentId:   0,
		DeptType:   sysDept.DeptType,
		DeptName:   sysDept.DeptName,
		DeptStatus: sysDept.DeptStatus,
		CreateTime: util.HTime{Time: time.Now()},
	}
	if sysDept.ParentId != 1 {
		data.ParentId = sysDept.ParentId
	}
	result := Db.Create(&data)
	if result.Error != nil {
		return false
	}
	return true
}

// QuerySysDeptVoList 部门下拉列表
func QuerySysDeptVoList() (sysDept []entity.SysDeptVo) {
	Db.Table("sys_dept").Select("dept_id,parent_id,dept_name").Scan(&sysDept)
	return sysDept
}

// UpdateSysDept 更新部门
func UpdateSysDept(dept entity.SysDept) bool {
	sysDept := GetSysDeptById(dept.DeptId)
	if sysDept.DeptId <= 0 {
		return false
	}
	deptName := GetSysDeptByName(dept.DeptName, dept.DeptId)
	if deptName.DeptId > 0 {
		return false
	}
	sysDept.ParentId = dept.ParentId
	sysDept.DeptType = dept.DeptType
	sysDept.DeptName = dept.DeptName
	sysDept.DeptStatus = dept.DeptStatus
	result := Db.Save(&sysDept)
	if result.Error != nil {
		return false
	}
	return true
}

// DeleteSysDept 删除部门
func DeleteSysDept(dto entity.SysDeptIdDto) error {
	sysAdmin := GetSysAdminByDept(dto.DeptId)
	if sysAdmin.AdminId > 0 {
		return errors.New("部门下存在管理员")
	}
	// 启动事务
	tx := Db.Begin()
	if err := tx.Error; err != nil {
		return err
	}
	if err := tx.Where("parent_id = ?", dto.DeptId).Delete(&entity.SysDept{}).Error; err != nil {
		tx.Rollback()
		return err
	}
	if err := tx.Delete(&entity.SysDept{}, dto.DeptId).Error; err != nil {
		tx.Rollback()
		return err
	}
	return tx.Commit().Error
}

// GetSysDeptList 获取部门列表
func GetSysDeptList(DeptName string, DeptStatus uint) (sysDept []entity.SysDept) {
	model := Db.Table("sys_dept")
	if DeptName != "" {
		model = model.Where("dept_name = ?", DeptName)
	}
	if DeptStatus != 0 {
		model = model.Where("dept_status = ?", DeptStatus)
	}
	model.Find(&sysDept)
	return sysDept
}
